/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rest.jbpm.execution;

import java.util.List;
import org.hibernate.*;
import org.jbpm.api.Execution;
import org.jbpm.api.cmd.*;
import org.jbpm.pvm.internal.util.CollectionUtil;
import org.slf4j.*;

/**
 *
 * @author jump
 */
public class FindProcessByVariable implements Command<List<Execution>> {

    private static final Logger log = LoggerFactory.getLogger(FindProcessByVariable.class);
    private static final String hql = 
    "SELECT execution FROM org.jbpm.pvm.internal.type.Variable variable "
    + "JOIN variable.execution as execution "
    + "WHERE variable.key=:name AND variable.string=:value";
    private final String name;
    private final String value;
    
    public FindProcessByVariable(String name, String value) {
        this.name = name;
        this.value = value;
    }
	
	@Override
	public List<Execution> execute(Environment environment)
			throws Exception {
        
        Session session = null;
        SessionFactory sessionFactory = environment.get(SessionFactory.class);
        try {
            
            session = sessionFactory.openSession();
            Query query = session.createQuery(hql);
            query.setParameter("name", name);
            query.setParameter("value", value);
            query.setFirstResult(0);
            return CollectionUtil.checkList(query.list(), Execution.class);
            
        } finally {
            if(session != null) session.close();
        }
	}
}
